<?


class NearestNeighbourClassifier
{
	private $dataSetPathSubj;
	private $dataSetPathObj;
	private	$dataSetSubj;
	private $dataSetObj;
	private $k;
	
	public function __construct($k)
	{
		$this -> dataSetSubj = array();
		$this -> dataSetObj = array();
		$this -> initializeDataSet();
		$this -> k = $k;
	}
	
	
	public function classify($sentence)
	{
		$distance = array();
		for ($i=0 ; $i < count($this->dataSetSubj) ; $i++)
		{
				$intersectSubj = array_intersect($sentence ,$this->dataSetSubj[$i]);
				$distSubj = count($sentence) - count($intersectSubj); 
				array_push($distance, array("dist" => $distSubj, "class" => 'subj'));					

				$intersectObj = array_intersect($sentence,$this -> dataSetObj[$i]);
				$distObj = count($sentence) - count($intersectObj); 
				array_push($distance, array("dist" => $distObj, "class" => 'obj'));
		}	
		
		return $this -> searchClass($distance);
	}
	
	
	
	private function searchClass($distance)
	{
		$this->array_sort_by_occ($distance, 'dist') ;

		$result = array();

		$maxDistance  = $this -> getMaxDistance($distance);

		for ($i = 0 ; $i < count($distance); $i++)
			if($distance[$i]['dist'] <= $maxDistance)
				array_push($result, $distance[$i]);
			else
				break;				
							

		$subj = 0;
		$obj = 0;

		foreach($result as $data)
		{
			if($data['class'] == 'subj')
				$subj++;
			else
				$obj++;
		}
		
		if($subj >= $obj)
			return 'subj';
		else	
			return 'obj';		
	}
	
	
	private function getMaxDistance($distance)
	{
		$max = array();
		foreach($distance as $current)
		{			
			if(count($max) == $this->k)
				return $max[($this->k)-1];

			
			if(!in_array($current['dist'], $max))
				array_push($max, $current['dist']);			
		}
	}
	private function array_sort_by_occ(&$arr, $col, $dir = SORT_ASC) 
	{
		$sort_col = array();
		foreach ($arr as $key=> $row) 
		{
			$sort_col[$key] = $row[$col];
		}
	
		array_multisort($sort_col, $dir, $arr);
	}

	
	private function initializeDataSet()
	{
		$this -> dataSetSubj = json_decode(file_get_contents("./ev/dataSetSubjEV.txt"), true);
		//echo '<pre>'.print_r($this->dataSetSubj, true).'</pre>';
		$this -> dataSetObj = json_decode(file_get_contents("./ev/dataSetObjEV.txt"), true);
		//echo '<pre>'.print_r($this -> dataSetObj, true).'</pre>';
	}
}


?>